package com.leyou.gateway.config;

import com.leyou.auth.utils.JwtUtils;
import com.leyou.auth.utils.UserInfo;
import com.leyou.common.utils.CookieUtils;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@EnableConfigurationProperties({JwtProperties.class, FilterProperties.class})
@Component
public class LoginFilter extends ZuulFilter {
    @Autowired
    private JwtProperties jwtProps;
    @Autowired
    private FilterProperties filterProps;

    @Override //过滤器类型
    public String filterType() {
        return "pre"; //请求再被路由之前拦截
    }

    @Override
    public int filterOrder() {
        return 1; //多个过滤器的时候,过滤器的执行顺序,数字越小优先级越高
    }

    @Override //判断该过滤器是否需要执行。返回true执行，返回false不执行
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext(); //获取上下文
        HttpServletRequest request = ctx.getRequest();//获取servletRequest
        String uri = request.getRequestURI(); //获取当前请求的uri
        //获取白名单的资源路径
        List<String> paths = filterProps.getAllowPaths();
        for (String path : paths) {
            if (uri.startsWith(path)) {
                return false;
            }
        }
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext(); //获取上下文
        HttpServletRequest request = ctx.getRequest();//获取servletRequest
        //获取token
        String token = CookieUtils.getCookieValue(request, jwtProps.getCookieName());
        try {
            // 校验通过什么都不做，即放行
            UserInfo userInfo = JwtUtils.getInfoFromToken(token, jwtProps.getPublicKey());
        } catch (Exception e) {
            // 校验出现异常，返回401 ,过滤掉该请求
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            e.printStackTrace();
        }
        return null;
    }
}
